import 'dart:math';
import 'package:mobx/mobx.dart';
import 'package:thal/backstage/blueprint/ai_chat_message_print.dart';

part 'ai_chat_room.g.dart';

/// AI聊天状态管理
class AiChatRoom = _AiChatRoom with _$AiChatRoom;

abstract class _AiChatRoom with Store {
  /// AI聊天消息列表
  @observable
  ObservableList<AiChatMessagePrint> aiMessages =
      ObservableList<AiChatMessagePrint>();

  /// 会话ID
  @observable
  String sessionId = '';

  /// 会话ID (conversation_id)
  @observable
  String? conversationId;

  /// 是否正在发送消息
  @observable
  bool isSending = false;

  /// 初始化会话ID
  @action
  void initSession() {
    if (sessionId.isEmpty) {
      final now = DateTime.now();
      final timeString =
          '${now.year}${now.month.toString().padLeft(2, '0')}${now.day.toString().padLeft(2, '0')}';
      final randomString =
          List.generate(16, (_) => Random().nextInt(10)).join();
      sessionId = '${timeString}_$randomString';
    }
  }

  /// 添加消息
  @action
  void addMessage(AiChatMessagePrint message) {
    aiMessages.add(message);
  }

  /// 设置会话ID
  @action
  void setConversationId(String id) {
    conversationId = id;
  }

  /// 设置发送状态
  @action
  void setSending(bool sending) {
    isSending = sending;
  }

  /// 清空消息
  @action
  void clearMessages() {
    aiMessages.clear();
    conversationId = null;
    sessionId = '';
  }
}
